//
//  DCWebViewController.m
//  DCProject
//
//  Created by bigbing on 2019/4/1.
//  Copyright © 2019 bigbing. All rights reserved.
//

#import "DCWebViewController.h"
#import <UINavigationController+FDFullscreenPopGesture.h>

@interface DCWebViewController ()

/** 进度条 */
@property (nonatomic, strong) NJKWebViewProgressView * progressView;
/** webview */
@property (nonatomic, strong) WKWebView                 *webView;
@property (nonatomic, strong) WeakScriptMessageDelegate * messgedele;
/** 请求 */
@property (nonatomic, strong) NSMutableURLRequest       *request;
/** 请求 */
@property (nonatomic, strong) NSString       *loadHtml;

@end

@implementation DCWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (!self.showNav) {
        self.fd_prefersNavigationBarHidden = YES;
        self.fd_interactivePopDisabled = NO;
    }else{
        self.title = self.titleString;
    }
    
    //    [self clearCache];
    [self.view addSubview:self.webView];
    [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
        if (!self.showNav) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
        }else{
            make.top.equalTo(self.view);
        }
        make.left.right.bottom.equalTo(self.view);
    }];
    
    if (self.request) {
        [self.webView loadRequest:self.request];
    }else if (self.loadHtml){
        [self.webView loadHTMLString:self.loadHtml baseURL:nil];
    }
}

-(void)removeSect{
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appGoBack"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appGetUserToken"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appGetCityName"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"canOpenWechat"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"canOpenAlipay"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toLoginApp"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goHome"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goShopping"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goPersonalCenter"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appShare"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toMineAppointment"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"customerService"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toShoppingCar"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toMineOrder"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toPayGoods"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"paySuccess"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"uploadImage"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"callPhone"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toSelectCity"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toNavigationLocation"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appSharePintuan"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appFindDetail"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"appGoParkVip"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"startWebView"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"getLatlon"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toNavigate"];
    
    //
    ////    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    //     [[NSNotificationCenter defaultCenter] removeObserver:self.webView];
    
    if (_webView) {
        [_webView.configuration.userContentController removeAllUserScripts];
        _messgedele.scriptDelegate = nil;
        _messgedele = nil;
    }
    
}
- (void)dealloc
{
    //   [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _messgedele.scriptDelegate = nil;
    _messgedele = nil;
    if (_webView) {
        [self removeSect];
        _webView.UIDelegate = nil;
        _webView.navigationDelegate = nil;
        _webView.scrollView.delegate = nil;
        [self clearCache];
    }
    
}

- (instancetype)initWithUrl:(NSString *)url
{
    NSString *st =[url
                   stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
                                                                       URLFragmentAllowedCharacterSet]];
    
    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:st]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    ////    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[url
    ////    stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
    ////    URLFragmentAllowedCharacterSet]]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    //    [request setValue:[NSString stringWithFormat:@"%@=%@",@"FirstPagecookie", @"FirstPagecookievalue"] forHTTPHeaderField:@"Cookie"];
    
    return [self initWithRequest:request];
}

- (instancetype)initWithRequest:(NSURLRequest *)request
{
    self = [super init];
    if (self) {
        
        self.request = request.mutableCopy;
    }
    return self;
}
- (instancetype)initWithHtml:(NSString*)html{
    self = [super init];
    if (self) {
        self.loadHtml = [NSString stringWithFormat:@"%@", html];
    }
    return self;
    
}

- (NJKWebViewProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[NJKWebViewProgressView alloc] initWithFrame:CGRectMake(0, 1, kScreenW, 3)];
        _progressView.progressBarView.backgroundColor = [UIColor dc_colorWithHexString:@"#3178F1"];
        _progressView.hidden = YES;
    }
    return _progressView;
}

- (WKWebView *)webView
{
    if (!_webView) {
        CGFloat bottomHeight = kStatusBarHeight > 20 ? 34 : 20;
        WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
        WKUserContentController* userContentController = [[WKUserContentController alloc] init];
        
        //         NSString *cookieStr = [NSString stringWithFormat:@"document.cookie ='%@=%@';",@"token",[DCObjectManager dc_readUserDataForKey:DC_Token_Key]];
        //        if (![DCObjectManager dc_readUserDataForKey:DC_Token_Key]) {
        //            cookieStr = @"";
        //        }
        //        WKUserScript * cookieScript = [[WKUserScript alloc]initWithSource:cookieStr                        injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        //        [userContentController addUserScript:cookieScript];
        wkConfig.userContentController = userContentController;
        //
        _messgedele = [[WeakScriptMessageDelegate alloc] initWithDelegate:self];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appGoBack"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appGetUserToken"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appGetCityName"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"canOpenWechat"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"canOpenAlipay"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toLoginApp"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"goHome"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"goShopping"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"goPersonalCenter"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appShare"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toMineAppointment"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"customerService"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toShoppingCar"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toMineOrder"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toPayGoods"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"paySuccess"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"uploadImage"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"callPhone"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toSelectCity"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toNavigationLocation"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appSharePintuan"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appFindDetail"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"appGoParkVip"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"startWebView"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"getLatlon"];
        [wkConfig.userContentController addScriptMessageHandler:_messgedele name:@"toNavigate"];
        
        
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, bottomHeight, kScreenW, kScreenH-bottomHeight) configuration: wkConfig   ];
        
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        
    }
    return _webView;
}

#pragma mark - WKWKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //    self.progressView.hidden = NO;
    [self.view bringSubviewToFront:self.progressView];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //    self.progressView.hidden = YES;
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    //    self.progressView.hidden = YES;
    
}

#pragma mark - 观察者响应

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if (self) {
        
    }else{
        return;
    }
    if ([message.name isEqualToString:@"appGoBack"]) {
        [self appGoBack];
    }
    NSLog(@"%@---%@", message.body,message.name);
}



- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    completionHandler([DCObjectManager dc_readUserDataForKey:DC_Token_Key]);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSURL *URL = navigationAction.request.URL;
    
    NSString *scheme = [URL scheme];
    
    if ([scheme isEqualToString:@"tel"]) {
        
        NSString *resourceSpecifier = [URL resourceSpecifier];
        
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
            
        });
        
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}

#pragma mark- 清除缓存
- (void)clearCache {
    if ([[[UIDevice currentDevice]systemVersion]intValue ] >= 9.0) {
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        }];
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}

#pragma mark - 交互方法
-(void)appGoBack{
    NSLog(@"返回");
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([self.webView canGoBack]) {
            [self.webView goBack];
        } else {
            //            if (self.navigationController.childViewControllers.count > 1) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
            //            } else {
            //                [self dismissViewControllerAnimated:YES completion:nil];
            //            }
        }
    });
}

@end


@implementation WeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}

@end
